package com.firstresponder.util;

import com.firstresponder.activity.FirstResponder;
import com.firstresponder.location.LocationService;
import com.firstresponder.util.SmsDecoder;
import com.firstresponder.db.FirstResponderDB;
import com.firstresponder.db.Location;

import java.util.ArrayList;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {

	public static final String TAG = "FR_SMSReceiver";
	private static FirstResponder MAIN_ACTIVITY = null;
	private static LocationService LOCATION_SERVICE = null;
	private SmsDecoder decoder = null;
	private boolean startAlert = false;
	private boolean endAlert = false;
	private boolean updateDestination = false;
	private boolean addDbDestination = false;

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "TEXT RECEIVED");
		Bundle bundle = intent.getExtras();

		ArrayList<SmsMessage> messages = new ArrayList<SmsMessage>();

		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");

			for (Object pdu : pdus) {
				SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
				messages.add(message);
				decoder = new SmsDecoder(message.getMessageBody());

				startAlert = decoder.isAlertMessage();
				Log.i("FROM","alertMessage: " + decoder.isAlertMessage());
				if (startAlert==false) {
					endAlert = decoder.isCancelMessage();
				}
				if (endAlert==false) {
					updateDestination = decoder.isUpdateDestination();
				}
				if (updateDestination==false) {
					addDbDestination = decoder.isAddDbDestination();
				}

				Log.i("FROM", message.getOriginatingAddress());
				Log.i("MESSAGE", message.getMessageBody());
			}
		}

		if (startAlert) {
			Log.i(TAG,"Incoming Start Alert message, Executing App");
			MessageSender sender = MessageSender.getInstance();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			String pnumber = prefs.getString("defaultnumber", "0000000000");
			Log.i("MessageSender","Phone number in file: " + pnumber);
			sender.setSmsNumber(pnumber);
			sender.setYesNumber(decoder.getYesNumber());
			sender.setNoNumber(decoder.getNoNumber());
			Intent myIntent = new Intent();
			myIntent.setClassName("com.firstresponder.activity",
					FirstResponder.class.getName());
			// Bundle data = new Bundle();
			// data.putString("body", messages.get(0).getMessageBody());
			// data.putString("from", messages.get(0).getOriginatingAddress());
			// myIntent.putExtras(data);
			myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Intent locationServiceIntent = new Intent();
			locationServiceIntent.setClassName("com.firstresponder.location",
					LocationService.class.getName());
			LocationService.setServiceStatus(LocationService.ALERT_MODE);
			context.startService(locationServiceIntent);
			Log.i(TAG, "Starting FirstRepsonder!!");
			context.startActivity(myIntent);
		} else if (endAlert) {
			Log.i(TAG,"Incoming Cancel Alert message, Exiting App");
			if (!MAIN_ACTIVITY.equals(null)) {
				// Intent activityIntent = new Intent(Intent.ACTION_MAIN);
				Intent serviceIntent = new Intent();
				// activityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				// activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// activityIntent.addCategory(Intent.CATEGORY_HOME);
				serviceIntent.setClassName("com.firstresponder.activity",
						FirstResponder.class.getName());
				Intent locationServiceIntent = new Intent();
				locationServiceIntent.setClassName(
						"com.firstresponder.location",
						LocationService.class.getName());
				LocationService.setServiceStatus(LocationService.PASSIVE_MODE);
				context.startService(locationServiceIntent);
				Log.i(TAG, "Stopping FirstResponder!!!");
				// if(BluetoothService.isRunning()){
				// context.stopService(serviceIntent);
				// }
				MAIN_ACTIVITY
						.finishScreenActivity("ALERT CANCELLED... Stopping Application");
			}
		} else if (updateDestination) {
			Log.i(TAG,"Incoming Update Destination message");
			ArrayList<String> coordinates = decoder.getDestCoordinates();
			String Latitude = coordinates.get(0);
			String Longitude = coordinates.get(1);
			if(LOCATION_SERVICE!=null){
				Location destination = new Location();
				destination.setCurrLat(Double.parseDouble(Latitude));
				destination.setCurrLong(Double.parseDouble(Longitude));
				LOCATION_SERVICE.setCurrDestination(destination);
				Log.i(TAG,"Successfully updated the Destination");
			}
		} else if (addDbDestination) {
			//Add a Destination to the Database
			Log.i(TAG,"Incoming Add Destination to DB message");
			Map<String,String> destmap = decoder.getNewDestination();
			FirstResponderDB db = new FirstResponderDB(context);
			try {
				com.firstresponder.db.Location dbLocation = new com.firstresponder.db.Location();
				dbLocation.setCurrLat(Double.parseDouble(destmap.get("lat")));
				dbLocation.setCurrLong(Double.parseDouble(destmap.get("long")));
				dbLocation.setDept_id(destmap.get("dept_id"));
				dbLocation.setLocation_key(destmap.get("loc_key"));
				dbLocation.setPriority(Integer.parseInt(destmap.get("loc_pr")));
				dbLocation.setShortName(destmap.get("loc_name"));
				if(db.getLocationByPriority(destmap.get("loc_pr"))==null){
					db.insertLocation(dbLocation);
					Log.i(TAG,"Successfully added to Database");
				}
				else{
					db.updateLocation(dbLocation);
					Log.i(TAG,"Successfully updated in Database");
				}
			} catch (SQLiteException e) {
				Log.e(TAG, Log.getStackTraceString(e));
			}
		}
	}

	public static void setMainActivity(FirstResponder firstResponder) {
		MAIN_ACTIVITY = firstResponder;
	}
	
	public static void serLocationService(LocationService locationservice){
		LOCATION_SERVICE = locationservice;
	}

}
